﻿using System;
using System.Data;
using System.IO;
using System.Linq;
using Microsoft.ApplicationBlocks.Data;
using NTTDATA.BEENChina.ResultCertification.Client.Entry.ServiceEntry;
using Ntt.NttData.Been.DeliveryCheck.DEntry.BeenWCFHelper;
using Ntt.NttData.Been.DeliveryCheck.Command; 

namespace NTTDATA.BEENChina.ResultCertification.Client.Entry.Logic
{
    public class ImageHelper
    {
        /* 
        private static string ConnectionString
        {
            get
            {
                  using (ServiceEntryClient client = new ServiceEntryClient())
                  {
                    return  client.GetImageBackupDatabaseConnstring();
                  }  
            }
        }

        private static string ImageFolder
        {
            get
            {
                using (ServiceEntryClient client = new ServiceEntryClient())
                {
                    return client.GetImageFolder();
                }
            }
        }
        private static string WcfAddress
        {
            get
            {
                using (ServiceEntryClient client = new ServiceEntryClient())
                {
                    return client.GetImageBackupServiceAddress();
                }

            }
        }

       private static VerfityJobItem GetWcfParam(VerfityJobItem item)
        {
            //string wcfParam = string.Empty;
            string wcfAddres = WcfAddress;
            string orderCodeWhere=string.Empty ;                        
            string[] orders = item.ChildImage.Select(o => o.OrderId).Distinct().ToArray();
            foreach (string orderId in orders)
            {
                orderCodeWhere += orderCodeWhere == string.Empty ? "OrderCode='" + orderId + "'" : " OR OrderCode='" + orderId +"'";
            }

            string sql = " SELECT  OrderCode,Note+'_'+SavePath  FROM b_FileDownLoad WHERE " +
                          " (" + orderCodeWhere+ " )  AND FileDownLoadState = 4 ";
            try
            {
                DataSet ds = SqlHelper.ExecuteDataset(ConnectionString, System.Data.CommandType.Text, sql);               
                foreach (ChildImage image in item.ChildImage )
                {                                                
                    DataRow[] rows = ds.Tables[0].Select( "ordercode='" + image.OrderId+"'");

                    if (rows.Any() )
                    {
                        string ipAndSavePaht = rows[0][1].ToString();

                        string childPicParam = string.Empty;

                        if (image.ImageId.Contains("-"))
                        {

                            childPicParam =
                             Path.Combine(  image.ImageId.Substring(image.ImageId.Length - 3) , image.ImageId) ;
                             

                        }

                        if (!String.IsNullOrEmpty(childPicParam))
                        {
                            image.ImageFullPath = Path.Combine(ipAndSavePaht, childPicParam + ".TIF");
                        }
                        else
                        {
                            image.ImageFullPath = ipAndSavePaht;
                            image.ImageFullPath = Path.Combine(image.ImageFullPath, image.ImageId + ".TIF");

                        }

                        //add image download address

                        if (image.ImageFullPath != null)
                        {
                            string[] splitInfo = image.ImageFullPath.Split(new char[] {'_'});
                            string imageFilePath = splitInfo[1];
                            
                            image.ImageDownLoadAddress = string.Format(wcfAddres, splitInfo[0]);
                            image.ImageDownLoadParam = imageFilePath;
                        }

                    }
                }                 
            }
            catch (Exception ex)
            {                
                throw ex;
            }

            return item;
        }*/

        public static void SaveImage(VerfityJobItem item)
        {
            string imageFolder = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
            if (System.IO.Directory.Exists(imageFolder))
            {
                System.IO.Directory.Delete(imageFolder, true);
            }

            System.IO.Directory.CreateDirectory(imageFolder);

            //item = GetWcfParam( item);
            // @"http://{0}:8080/SPCC/DeliveryCheck.WEntry.svc";
 
            foreach (ChildImage image in item.ChildImage)            
            {
                if (image.ImageFullPath != null)
                {
                    //此段代码转移到服务端
                    //string[] splitInfo = image.ImageFullPath.Split(new char[] { '_' });
                    //string imageFilePath = splitInfo[1];
                    //WCFHelper.Url = string.Format(wcfAddres, splitInfo[0]);

                    //WCFHelper.Url = image.ImageDownLoadAddress;
                    //ImageInformation imageData = WCFHelper.GetInstance().TRunFileDownLoad("1", image.ImageDownLoadParam);

                    //本次工作结束 清空 否则出错
                    //WCFHelper.GetInstance().ClearWcf();
                    //System.IO.File.WriteAllBytes(image.ImageFullPath, imageData.Image);

                    image.ImageFullPath = System.IO.Path.Combine(imageFolder, image.ImageId);
                    
                    System.IO.File.WriteAllBytes(image.ImageFullPath, image.ImageData);

                }
                else
                {
                   /* 
                    * //Ns画像位置
                    string imageDir = ImageFolder;

                    if (!String.IsNullOrEmpty(LoginHelper.GetInstance().OrderDate))
                    {
                        //Ns文件夹 + orderdate(joblist 画面上时间)
                        imageDir = Path.Combine(imageDir, LoginHelper.GetInstance().OrderDate);
                    }


                    string[] files = null;
                    
                    if (  imageDir != null  &&   Directory.Exists(imageDir))
                    {
                         files = Directory.GetFiles(imageDir, image.ImageId + "*", SearchOption.AllDirectories);
                    }


                    if (files != null && files.Any())
                    {
                        image.ImageFullPath = System.IO.Path.Combine(imageFolder, image.ImageId);

                        System.IO.File.Copy(files[0], image.ImageFullPath,true);
                    }
                    else
                    {
                        string bakImage = System.IO.Path.Combine(Environment.CurrentDirectory, @"lib\UICheck.dll");

                        image.ImageFullPath = System.IO.Path.Combine(imageFolder, image.ImageId);

                        System.IO.File.Copy(bakImage, image.ImageFullPath,true);
                    }*/

                    string bakImage = System.IO.Path.Combine(Environment.CurrentDirectory, @"lib\UICheck.dll");

                    image.ImageFullPath = System.IO.Path.Combine(imageFolder, image.ImageId);

                    System.IO.File.Copy(bakImage, image.ImageFullPath, true);
                }
            }
        }
    }
}